import store from '@/store' // 状态管理
import {
	isWechat,
	buildPageUrl,
	encodeRedirectUrl
} from '@/common/util.js'
import {
	oncePay
} from '../api/order.js'
import {
	recharge
} from '../api/fund.js'
import {
	saveSubscribe
} from '../api/user.js'
import {
	getMpConfig
} from '../api/common.js'
import Request from './request.js'
import Config from '../config.js'

export const http = new Request();

// 设置全局配置
http.setConfig((config) => {
	config.baseUrl = Config.baseUrl;
	config.header = {
		'Content-Type': 'application/json;charset=UTF-8'
	};

	return config
})


// 请求之前拦截器
http.interceptor.beforeRequest((config, cancel) => {
	console.log('请求前拦截', config.url, config)

	// 登录校验
	let accessToken = store.getters.accessToken;
	console.log('get.accessToken', accessToken);
	if (!accessToken && !config.muteLogin) {
		console.error('needLogin request');
		cancel('登录过期，尝试重试'); // 取消请求
		console.info('needLogin request', 'silentReload');
		silentReload(config.curd === 'save');
		return;
	}

	// 平台
	// #ifdef  MP-WEIXIN
	config.url += (config.url.indexOf('?') !== -1 ? '&' : '?') + 'platform=MP-WEIXIN'
	// #endif
	// #ifdef  H5
	config.url += (config.url.indexOf('?') !== -1 ? '&' : '?') + 'platform=H5'
	// #endif

	// 认证token
	if (accessToken) {
		config.url += (config.url.indexOf('?') !== -1 ? '&' : '?') + 'token=' + accessToken
	}

	// 门店ID
	let shopId = store.getters.shopId;
	console.log('get.shopId', shopId);
	if (shopId) {
		config.url += (config.url.indexOf('?') !== -1 ? '&' : '?') + 'shop_id=' + shopId
	}

	// config.header['Cookie'] = 'token=' + accessToken;  // uploadFile时，不能传header，慎用这种方式

	return config;
})

// 请求之后拦截器 
http.interceptor.afterRequest((response) => {
	console.log('请求后拦截', response);

	// 系统错误
	if (response.statusCode === 500) {
		console.error('系统错误');
		setTimeout(() => {
			uni.showToast({
				title: '系统错误',
				icon: 'none',
				mask: true,
				duration: 2000
			})
		}, 50);
		return [response];
	}

	let data = response.data;

	// 网络错误
	if (!data) {
		console.error('网络错误');
		setTimeout(() => {
			uni.showToast({
				title: '网络错误',
				icon: 'none',
				mask: true,
				duration: 2000
			})
		}, 50)
		return [response];
	}

	if (typeof data === 'string') {
		data = JSON.parse(data)
	}

	// 正常请求
	if (data.code === 1) {
		return [0, data.data, data.msg];
	}

	// 系统错误
	console.warn('invalid request', data.msg);
	switch (data.code) {
		case 401: // 认证失败
			console.error('needLogin 401');
			store.commit('delAccessToken'); // 删除token
			console.info('needLogin 401', 'silentReload');
			silentReload(response.config.curd === 'save');
			break;
		case 402: // 自动登录失败
			break;
		default: // 错误提示
			setTimeout(() => {
				uni.showToast({
					title: data.msg || '网络错误',
					icon: 'none',
					mask: true,
					duration: 2000
				})
			}, 50)
			break;
	}

	return [response];
})

/**
 * 自动登录
 */
export function silentReload(warning = false, redirectUrl = null, ignoreConfig = false) {
	console.info('silentReload', warning, redirectUrl, ignoreConfig)
	if (warning) {
		setTimeout(() => {
			uni.showToast({
				title: '鉴权失败，请重新操作',
				icon: 'none',
				mask: true,
				duration: 2000
			})
		}, 50)
		return false
	}

	// 并发处理
	if (!ignoreConfig) {
		if (store.getters.isLock('silentReload')) {
			return false
		}
		store.commit('lock', 'silentReload')
		setTimeout(() => {
			// 2秒后清理锁
			store.commit('unlock', 'silentReload')
		}, 2000)
	}
	console.info('try login', 'silentReload')

	// 配置未正确加载
	const globalConfig = store.getters.globalConfig
	if (!globalConfig || Object.keys(globalConfig).length === 0) {
		if (ignoreConfig) {
			console.log('load config fail', 'silentReload')
			setTimeout(() => {
				uni.reLaunch({
					url: '/pages/user/tips?cont=配置加载失败，请尝试重新进入'
				})
			}, 50)
		} else {
			console.log('wait to load config', 'silentReload')
			setTimeout(() => {
				silentReload(warning, redirectUrl, true)
			}, 800)
		}
		return true;
	}

	// 跳转页面
	if (redirectUrl === null) {
		redirectUrl = getRedirectUrl()
		console.log('getRedirectUrl', redirectUrl, 'silentReload')
	}

	// #ifdef  MP-WEIXIN
	console.info('mini_login', 'silentReload')
	// 微信小程序自动登录
	uni.reLaunch({
		url: '/pages/user/mini_login?from=' + encodeRedirectUrl(redirectUrl)
	})
	// #endif

	// #ifdef  H5
	if (isWechat()) {
		if (store.getters.globalConfig.mp_login) {
			console.info('mp_login', 'silentReload')
			// 微信公众号自动登录
			uni.reLaunch({
				url: '/pages/user/mp_login?from=' + encodeRedirectUrl(redirectUrl)
			})
		} else {
			console.info('smartLogin', 'silentReload')
			// 智能跳转
			smartLogin(redirectUrl, true)
		}
	} else {
		if (store.getters.globalConfig.only_mp) {
			console.info('请在微信中打开', 'silentReload')
			uni.reLaunch({
				url: '/pages/user/tips?cont=请在微信中打开'
			})
		} else {
			console.info('smartLogin', 'silentReload')
			// 智能跳转
			smartLogin(redirectUrl, true)
		}
	}
	// #endif

	return true
}

/**
 * 进入登录页面
 */
export function smartLogin(redirectUrl, onceJump = false) {
	console.log('smartLogin', redirectUrl, onceJump)
	let needLogin = true
	const openUrls = ['content/', 'user/login', 'user/auto_login', 'user/mp_login', 'user/tips', 'user/setting']
	openUrls.filter((item, index) => {
		if (redirectUrl.indexOf('pages/' + item) !== -1) {
			needLogin = false
		}
	})

	// 不需要跳转
	if (onceJump && !needLogin) {
		console.log('keep current', 'smartLogin')
		return true
	}

	// 立即跳转
	setTimeout(() => {
		console.log('relanuch', 'smartLogin')
		uni.reLaunch({
			url: needLogin ? '/pages/user/login' : redirectUrl
		})
	}, 50)

	return true
}

export function getRedirectUrl() {
	let redirectUrl = '/pages/home/index'
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	if (currentPage) {
		if (currentPage.$page) {
			redirectUrl = currentPage.$page.fullPath
		}
	}

	return redirectUrl
}

export function registerJsapi() {
	// #ifdef  H5
	if (!isWechat()) {
		return
	}
	const site = window.location.href.substr(0, window.location.href.indexOf('#'))
	getMpConfig(site).then(([err, res]) => {
		console.log('getMpConfig', err, res)
		if (!err) {
			wx.config({
				debug: false,
				appId: res.appId,
				timestamp: res.timestamp,
				nonceStr: res.nonceStr,
				signature: res.signature,
				jsApiList: [
					'checkJsApi', // 判断当前客户端版本是否支持指定JS接口  
					'onMenuShareAppMessage', // 分享接口  
					'getLocation', // 获取位置  
					'openLocation', // 打开位置
					'scanQRCode', // 扫一扫接口  
					'chooseWXPay', // 微信支付  
					'chooseImage', // 拍照或从手机相册中选图接口  
					'previewImage', // 预览图片接口  
					'uploadImage' // 上传图片  
				]
			})
		}
	})
	// #endif
}

/**
 * 发起支付
 */
export function requestPayment(orderNo, payAlias, from) {
	console.log('requestPayment', orderNo, payAlias)
	// #ifdef  MP-WEIXIN
	let payChannel = 'wechat-miniapp'
	// #endif
	// #ifdef  H5
	let payChannel = 'wechat-mp'
	// #endif
	oncePay(orderNo, payChannel).then(([err, res]) => {
		console.log('oncePay', err, res)
		if (!err) {
			// #ifdef  MP-WEIXIN
			uni.requestPayment(res.payment_data).then(([err, res]) => {
				console.log('uni.requestPayment', err, res)
				let redirectUrl = null
				if (!err) {
					showToast('支付成功')
					if (from !== 'onceOrder') {
						redirectUrl = '/pages/order/detail?rder_no=' + orderNo
					}
				}
				if (from === 'onceOrder') {
					redirectUrl = '/pages/order/detail?submit=1&order_no=' + orderNo
				}
				if (redirectUrl) {
					setTimeout(() => {
						uni.reLaunch({
							url: redirectUrl
						})
					}, 1000)
				}
			})
			// #endif

			// #ifdef  H5
			wx.chooseWXPay({
				timestamp: res.payment_data.timeStamp,
				nonceStr: res.payment_data.nonceStr,
				package: res.payment_data.package,
				signType: res.payment_data.signType,
				paySign: res.payment_data.paySign,
				complete: function(res) {
					console.log('wx.chooseWXPay complete', res)
					let redirectUrl = null
					if (res.errMsg == 'chooseWXPay:ok' ||
						res.errMsg == 'getBrandWCPayRequest:ok' ||
						res.errMsg == 'get_brand_wcpay_request:ok') {
						showToast('支付成功')
						if (from !== 'onceOrder') {
							redirectUrl = '/pages/order/detail?rder_no=' + orderNo
						}
					}
					if (from === 'onceOrder') {
						redirectUrl = '/pages/order/detail?submit=1&order_no=' +
							orderNo
					}
					if (redirectUrl) {
						setTimeout(() => {
							uni.reLaunch({
								url: redirectUrl
							})
						}, 1000)
					}
				}
			})
			// #endif
		} else {
			if (from === 'onceOrder') {
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/order/detail?submit=1&order_no=' + orderNo
					})
				}, 1000)
			} else if (err.data.msg === '超时结束') {
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/order/detail?order_no=' + orderNo
					})
				}, 1000)
			}
		}
	})
}

/**
 * 发起充值
 */
export function requestRecharge(patchId, payAlias) {
	console.log('requestRecharge', patchId, payAlias)
	return new Promise((resolve, reject) => {
		// #ifdef  MP-WEIXIN
		let payChannel = 'wechat-miniapp'
		// #endif
		// #ifdef  H5
		let payChannel = 'wechat-mp'
		// #endif
		recharge(patchId, payChannel).then(([err, res]) => {
			console.log('recharge', err, res)
			if (!err) {
				// #ifdef  MP-WEIXIN
				uni.requestPayment(res.payment_data).then(([err, res]) => {
					console.log('uni.requestPayment', err, res)
					if (!err) {
						showToast('支付成功')
					}
					resolve([err, res])
				})
				// #endif

				// #ifdef  H5
				wx.chooseWXPay({
					timestamp: res.payment_data.timeStamp,
					nonceStr: res.payment_data.nonceStr,
					package: res.payment_data.package,
					signType: res.payment_data.signType,
					paySign: res.payment_data.paySign,
					complete: function(res) {
						console.log('wx.chooseWXPay complete', res)
						if (res.errMsg == 'chooseWXPay:ok' ||
							res.errMsg == 'getBrandWCPayRequest:ok' ||
							res.errMsg == 'get_brand_wcpay_request:ok') {
							showToast('支付成功')
							resolve([null, res])
						} else {
							showToast(res.errMsg)
							resolve([res, null])
						}
					}
				})
				// #endif
			} else {
				resolve([err, res])
			}
		})
	})
}

export function subscriberMessage(templateIds) {
	console.log('subscriberMessage', templateIds)
	return new Promise((resolve, reject) => {
		uni.requestSubscribeMessage({
			tmplIds: templateIds
		}).then(([err, res]) => {
			console.log('requestSubscribeMessage', err, res)
			if (!err) {
				let acceptTemplateIds = [];
				templateIds.forEach((item, index, array) => {
					if (res[item] == 'accept') {
						acceptTemplateIds.push(item)
					}
				})
				console.log('acceptTemplateIds', acceptTemplateIds)
				if (acceptTemplateIds.length > 0) {
					saveSubscribe(acceptTemplateIds).then(([err, res]) => {
						console.log('saveSubscribe', err, res)
					})
				}
			}
			resolve([err, res])
		})
	})
}

export function showToast(text, icon) {
	return uni.showToast({
		title: text || '加载中',
		icon: icon || 'none',
		mask: true,
		duration: 2000
	})
}